package com.reiuy.service.impl;

import com.reiuy.dao.CartDao;
import com.reiuy.dao.GoodDao;
import com.reiuy.dao.UserDao;
import com.reiuy.entity.Cart;
import com.reiuy.vo.Cartinfo;
import com.reiuy.entity.Good;
import com.reiuy.entity.User;
import com.reiuy.service.CartService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CartServiceImpl implements CartService {
    @Resource
    private CartDao cartDao;

    @Resource
    private UserDao userDao;

    @Resource
    private GoodDao goodDao;

    @Override
    public int addcart(User user, Good good, Integer quantity) {


        Cart cart = new Cart();
        cart.setGoodid(good.getGoodid());
        User user_temp;
        user_temp = userDao.selectUesrIdByname(user);
        //创建一个user_temp用于接收dao对象中selectUserIdByname的返回user
        //这是一个包含着使用购物车用户的username(session中)所代表的userid信息的user对象

        //对被加入购物车的商品进行判断,是否是用户自己的商品
        if (goodDao.selectSelleridById(good).getSellerid() .equals(user_temp.getUserid())) {
            return -2;
            //如果用户将自己的商品加入了购物车,则直接返回-2,作为标识用户将自己的商品加入购物车的错误
        } else {
            List<Cartinfo> cartinfos = cartDao.selectusercart(user_temp);
            if (cartinfos != null) {
                for (int i = 0; i < cartinfos.size(); i++) {
                    if (good.getGoodid().equals(cartinfos.get(i).getGoodid())) {
                        quantity = quantity + cartinfos.get(i).getQuantity();
                        Cart cart_temp = new Cart();
                        cart_temp.setCartid(cartinfos.get(i).getCartid());
                        cart_temp.setQuantity(quantity);

                        return cartDao.updatequantity(cart_temp);
                    }
                }
            }
            //无记录时插入记录
            cart.setOwnerid(user_temp.getUserid());
            cart.setQuantity(quantity);
            //TODO 此处需要加入对于cart中记录的state属性进行判断的逻辑
            return cartDao.insertintocart(cart);
        }
    }


    @Override
    public List<Cartinfo> foundusercart(User user) {
        User user_temp;
        user_temp = userDao.selectUesrIdByname(user);
        //使用username找到userid

        return cartDao.selectusercart(user_temp);
        //返回cartinfo集合
    }


    @Override
    public int deletecart(Cart cart) {
        return cartDao.deletegoodincart(cart);
    }
}
